package org.fingersnow.dbdictionary;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.fingersnow.dbdictionary.dto.DataBase;
import org.fingersnow.dbdictionary.dto.Table;
import org.fingersnow.utils.DateUtils;

import com.alibaba.fastjson.JSONArray;

public class Json2DataBase {
	
	/**
	 * 	获取文件内容
	 * @param fileName classpath下 json 文件名
	 * @return
	 * @throws URISyntaxException 
	 * @throws IOException 
	 */
	private static String getJsonString(String fileName) throws URISyntaxException, IOException {
		if (null != fileName && !"".equals(fileName.trim())) {
			fileName = "dbStructure.json";
		}
		URL path = Thread.currentThread().getContextClassLoader().getResource(fileName);
		StringBuffer buffer = new StringBuffer();
		BufferedReader bf= null;
		try {
			bf = new BufferedReader(new FileReader(new File(path.toURI())));
			String s = null;
	        while((s = bf.readLine()) !=null){
	            buffer.append(s.trim());
	        }
	        return buffer.toString();
		} finally {
			bf.close();
		}
	}
	
	private static List<Table> jsonString2Table(String json) {
		if(null == json ||"".equals(json.trim())) {
			return new ArrayList<>(0);
		}
		return JSONArray.parseArray(json, Table.class);
	}
	
	public static DataBase getDataBase(String author,String version,String fileName) throws URISyntaxException, IOException {
		DataBase db = new DataBase();
		db.setAuthor(null == author||"".equals(author)?"system":author);
		db.setVersion(null == version||"".equals(version)?"V1.1":version);
		db.setDate(DateUtils.getCurrentDateString("yyyy-MM-dd"));
		db.setTables(jsonString2Table(getJsonString(fileName)));
		return db;
	}
}
